<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Annotation\ModuleAndAction;
use App\Controller\AbstractController;
use App\Helper\ApiHelper;
use App\Helper\FileHelper;
use App\Middleware\AdminMiddleware;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ResponseInterface;

/**
 * @AutoController()
 * @Middleware(AdminMiddleware::class)
 */
class DbLogController extends AbstractController
{
    const LOG_PATH = BASE_PATH . '/storage/adminLog';

    /**
     * @ModuleAndAction(module="管理后台:系统设置:系统日志", action="查看", icon="fa fa-database")
     */
    public function list(): ResponseInterface
    {
        $data = [];
        $files = FileHelper::getFileSystem()->files(static::LOG_PATH);
        foreach ($files as $file) {
            array_push($data, [
                'name' => $file->getFilename(),
                // 'path' => $file->getPathname(),
            ]);
        }
        return $this->response->json(ApiHelper::genSuccessData($data, count($data)));
    }

    /**
     * @ModuleAndAction(module="管理后台:系统设置:系统日志", action="查看")
     */
    public function download(): ResponseInterface
    {
        $fileName = $this->request->query('file', '');
        if (empty($fileName)) {
            return $this->response->redirect('/404.html');
        }
        $file = FileHelper::checkPath(static::LOG_PATH . '/' . $fileName, static::LOG_PATH);
        if ($file && file_exists($file) && is_file($file)) {
            return $this->response->download($file, $fileName);
        }
        return $this->response->redirect('/404.html');
    }

    /**
     * @ModuleAndAction(module="管理后台:系统设置:系统日志", action="删除")
     */
    public function delete(): ResponseInterface
    {
        $fileName = $this->request->post('file', '');
        if (empty($fileName)) {
            return $this->response->json(ApiHelper::genErrorData());
        }
        $file = FileHelper::checkPath(static::LOG_PATH . '/' . $fileName, static::LOG_PATH);
        if ($file && file_exists($file) && is_file($file) && FileHelper::del($file)) {
            return $this->response->json(ApiHelper::genSuccessData());
        }
        return $this->response->json(ApiHelper::genErrorData());
    }
}
